﻿using CommunityToolkit.Mvvm.Input;
using HandyControl.Data;
using Koala.Pro.Common;
using Koala.Pro.Common.Extension;
using Koala.Pro.Core.Models;
using Koala.Pro.Helpers;
using Koala.Pro.Services;
using Koala.Pro.ViewModels;
using System.Data;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Wpf.Ui.Controls;

namespace Koala.Pro.Views.Pages
{
    public partial class OuListPage : Page, INavigableView<OuListViewModel>
    {
        public OuListViewModel ViewModel { get; }

        public OuListPage()
        {
            InitializeComponent();
        }

        public OuListPage(OuListViewModel viewModel)
        {
            ViewModel = viewModel;
            base.DataContext = this;
            InitializeComponent();
            ViewModel.GetTreeCommand.ExecuteAsync(null);
        }

        [RelayCommand]
        private async Task Add()
        {
            await Edit(null);
        }

        [RelayCommand]
        private async Task EditById(string id)
        {
            if (!id.IsNullOrEmpty())
            {
                OuEditPage page = App.GetService<OuEditPage>();
                OuEditViewModel viewModel = page.ViewModel;
                viewModel.Item = await BLLFactory<IOuService>.Instance.GetAsync(id.ToInt32());
                await page.ViewModel.InitData(id.ToInt32());
                page.ViewModel.IsEdit = true;
                page.ShowDialog();
           
                if (page.ViewModel.Result?.Success == true)
                {
                    await ViewModel.GetData();
                }
            }
        }

        [RelayCommand]
        private async Task Edit(OuInfo info)
        {
            OuEditPage page = App.GetService<OuEditPage>();
            if (info != null)
            {
                OuEditViewModel viewModel = page.ViewModel;
                viewModel.Item = await BLLFactory<IOuService>.Instance.GetAsync(info.Id);
                await page.ViewModel.InitData(info.Id);
                page.ViewModel.IsEdit = true;
                page.Height = 680.0;
                page.Width = 800.0;
            }
            else
            {
                page.ViewModel.Item = new OuInfo
                {
                    Creator_ID = App.ViewModel.UserInfo.Id.ToString()
                };
                page.ViewModel.UserInfos.Clear();
                page.ViewModel.RoleInfos.Clear();
                page.ViewModel.IsEdit = false;
                page.Height = 600.0;
                page.Width = 800.0;
                page.ViewModel.Item.PID = (ViewModel.PageDto.PID.HasValue ? ViewModel.PageDto.PID : App.ViewModel.UserInfo.Dept_ID?.ToInt32());
            }
            page.ShowDialog();
        
            if (page.ViewModel.Result?.Success == true)
            {
                await ViewModel.GetData();
            }
        }

        [RelayCommand]
        private async Task Delete(OuInfo info)
        {
            await ViewModel.DeleteCommand.ExecuteAsync(info);
            await ViewModel.GetData();
        }

        [RelayCommand]
        private void Search()
        {
            ViewModel.PageDto.PID = null;
            ViewModel.PageDto.Company_ID = null;
            ViewModel.SearchCommand.ExecuteAsync(null);
        }

        private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!(sender is System.Windows.Controls.DataGrid { SelectedItems: var selectedItems }))
            {
                return;
            }
            if (selectedItems != null)
            {
                List<OuInfo> list = new List<OuInfo>();
                foreach (OuInfo item in selectedItems)
                {
                    list.Add(item);
                }
                ViewModel.SelectedItems = list;
            }
            else
            {
                ViewModel.SelectedItems = null;
            }
        }

        [RelayCommand]
        private void ImportExcel()
        {
            var importPage = App.GetService<ImportExcelPage>();
            importPage.ViewModel.Items?.Clear();
            importPage.ViewModel.TemplateFile = "机构（部门）信息-模板.xls";
            importPage.OnDataSave -= ExcelData_OnDataSave;
            importPage.OnDataSave += ExcelData_OnDataSave;
            ViewModel.Navigate(typeof(ImportExcelPage));
        }

        private string GetRowData(DataRow row, string columnName)
        {
            string result = "";
            if (row.Table.Columns.Contains(columnName))
            {
                result = row[columnName].ToString();
            }
            return result;
        }

        private async Task<bool> ExcelData_OnDataSave(DataRow dr)
        {
            DateTime dateTime = Convert.ToDateTime("1900-01-01");
            OuInfo ouInfo = new OuInfo();
            ouInfo.PID = GetRowData(dr, "父ID").ToInt32();
            ouInfo.HandNo = GetRowData(dr, "机构编码");
            ouInfo.Name = GetRowData(dr, "机构名称");
            ouInfo.SortCode = GetRowData(dr, "排序码");
            ouInfo.Category = GetRowData(dr, "机构分类");
            ouInfo.Address = GetRowData(dr, "机构地址");
            ouInfo.OuterPhone = GetRowData(dr, "外线电话");
            ouInfo.InnerPhone = GetRowData(dr, "内线电话");
            ouInfo.Note = GetRowData(dr, "备注");
            ouInfo.Creator = GetRowData(dr, "创建人");
            ouInfo.Creator_ID = GetRowData(dr, "创建人ID");
            string rowData = GetRowData(dr, "创建时间");
            if (!string.IsNullOrEmpty(rowData))
            {
                if (DateTime.TryParse(rowData, out var result) && result > dateTime)
                {
                    ouInfo.CreateTime = result;
                }
            }
            else
            {
                ouInfo.CreateTime = DateTime.Now;
            }
            ouInfo.Company_ID = GetRowData(dr, "所属公司ID");
            ouInfo.CompanyName = GetRowData(dr, "所属公司名称");
            return await BLLFactory<IOuService>.Instance.InsertAsync(ouInfo);
        }

        private async void deptTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (e.NewValue is RoleAndDeptTreeNode roleAndDeptTreeNode)
            {
                ViewModel.DeptTreeModel.SelectNode = roleAndDeptTreeNode;
                ViewModel.PageDto.Company_ID = roleAndDeptTreeNode.CompanyId;
                ViewModel.PageDto.PID = roleAndDeptTreeNode.DeptId?.ToInt32();
                await ViewModel.GetData();
            }
        }

        private void SearchBar_OnSearchStarted(object sender, FunctionEventArgs<string> e)
        {
            ViewModel.DeptTreeModel.SearchKey = e.Info;
            if (e.Info.IsNullOrEmpty())
            {
                ViewModel.DeptTreeModel.FilteredTreeItems = ViewModel.DeptTreeModel.TreeItems;
                return;
            }
            ViewModel.DeptTreeModel.FilteredTreeItems = ViewModel.DeptTreeModel.TreeItems.FindRoleNodes((RoleAndDeptTreeNode s) => s.Name.Contains(e.Info, StringComparison.OrdinalIgnoreCase));
        }

        private async void deptTree_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (deptTree.SelectedItem is RoleAndDeptTreeNode roleAndDeptTreeNode)
            {
                OuInfo ouInfo = await BLLFactory<IOuService>.Instance.GetAsync(roleAndDeptTreeNode.DeptId.ToInt32());
                if (ouInfo != null)
                {
                    await Edit(ouInfo);
                }
            }
        }
    }
}
